<?php

namespace App\Ant\Jobs;

use App\Ant\UrlIterator;
use App\Models\GenerateUrl;
use App\Models\PushUrl;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Bus\Queueable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Support\Collection;

class GenerateJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    /**
     * 任务最大尝试次数。
     *
     * @var int
     */
    public $tries = 5;

    /**
     * 任务运行的超时时间。
     *
     * @var int
     */
    public $timeout = 1200;

    protected $urls;

    protected $status;

    /**
     * 创建一个新的任务实例。
     *
     * @return void
     */
    public function __construct($status)
    {
        $this->urls = new Collection();
        $this->status = $status;
    }

    /**
     * 运行任务。
     *
     * @return void
     * @throws \Throwable
     */
    public function handle()
    {
        \DB::transaction(function () {
            $max = PushUrl::where('generate_status', false)->limit(100000)->max('id');
            PushUrl::where('generate_status', false)->where('id', '<', $max)->chunk(1000, function ($items) {
                $pushUrls = $items->groupBy('site')->toArray();
                foreach (new UrlIterator($pushUrls, $this->status) as $item) {

                }
                unset($items);
            });

        });
    }
}